#*******************************************************************************
# Park file, keeps specific information about a wind park together
# Not sure about the implementation, it is kind of mimicking
# object-oriented programming but using .py files instead of objects
#
# Really not sure whether we should be defining different read() methods
# but each park has slightly different set of variables
#*******************************************************************************

import numpy as np
import matplotlib as mpl
import tables as tb
from powercurve import powercurve

h5fname        = 'C:\UnBackedUp_Data\h5\kentish_10_minute_array.h5'
name           = 'kentish'
turbine_pcurve = powercurve.fromfile1D(r'H:\Data\pcurves\turbine\vestas_V90_3MW.csv')
interval       = '10m'


tbids = [ 'UKFA01', 'UKFA02', 'UKFA03', 'UKFA04', 'UKFA05',
             'UKFB01', 'UKFB02', 'UKFB03', 'UKFB04', 'UKFB05',
             'UKFC01', 'UKFC02', 'UKFC03', 'UKFC04', 'UKFC05',
             'UKFD01', 'UKFD02', 'UKFD03', 'UKFD04', 'UKFD05',
             'UKFE01', 'UKFE02', 'UKFE03', 'UKFE04', 'UKFE05',
             'UKFF01', 'UKFF02', 'UKFF03',  'UKFF04', 'UKFF05']

front_turbine = 'UKFA05'
pairs = [('UKFA05', 'UKFB05'), ('UKFA05', 'UKFB04'), ('UKFA05', 'UKFA04')]

def front_row(d):
    raise Exception('not implemented for Kentish')

def read_turbines():
    h5f         = tb.openFile(h5fname, mode='r')

    #
    # Turbine variables
    #
    group       = h5f.root.turbines
    tbids       = group.tbid.read()
    dates       = group.utctimestamp.read()
    timestamp   = np.array(mpl.dates.num2date(dates))
    pwr         = np.ma.array(group.ActivePower.read())
    spd         = np.ma.array(group.WindSpeed.read())
    yaw         = np.ma.array(group.NacelleDirection.read())
    pitch       = np.ma.array(group.BladePitchAngle.read())

    #
    # First mask any non-sensical data
    #
    yaw.mask   = np.isnan(yaw)
    spd.mask   = (spd<0) | (np.isnan(spd))

    h5f.close()
    return tbids, timestamp, pwr, yaw, spd, pitch


def read_met():
    h5f         = tb.openFile(h5fname, mode='r')

    #
    # Met variables
    #
    group       = h5f.root.met
    met_spd     = np.ma.array(group.MetStation73_WindSpeed1.read())
    #met_spd     = np.ma.array(group.M01_Windspeed.read())
    met_dir     = np.ma.array(group.MetStation73_WindDirection1.read())
    #met_dir     = np.ma.array(group.M01_Winddirection.read())

    print met_spd.shape
    print met_dir.shape
    met_spd.mask  = (met_spd<0) | (np.isnan(met_spd))
    met_dir.mask  = np.isnan(met_dir)

    h5f.close()
    return met_spd, met_dir


